<template>
	<view class="checkout-page">

		<!-- 商品列表 -->
		<view class="products-title">商品</view>
		<view class="product-item" v-for="(item, index) in cartList" :key="index">
			<image :src="item.imageUrl" mode="widthFix" class="product-img"></image>
			<view class="product-info">
				<view class="product-name">{{ item.name }}</view>
				<view class="product-spec" v-if="item.spec">{{ item.spec }}</view>
				<view class="product-price-count">
					<text
						class="product-price">¥{{ typeof item.price === 'number' ? item.price.toFixed(2) : 'NAN' }}</text>
					<text class="product-count">x{{ item.quantity }}</text>
				</view>
			</view>
		</view>

		<!-- 支付方式 -->
		<view class="payment-method">
			<view class="method-title">支付方式</view>
			<view class="method-options">
				<view class="method-option" :class="{ 'selected': selectedPayment === 'balance' }"
					@click="selectPayment('balance')">
					<view class="method-icon">
						<uni-icons type="logo-balance" size="24" color="#07C160"></uni-icons>
					</view>
					<view class="method-name">余额</view>
					<view class="method-select" v-if="selectedPayment === 'balance'">
						<uni-icons type="checkmark" size="20" color="#0000ff"></uni-icons>
					</view>
				</view>
				<view class="method-option" :class="{ 'selected': selectedPayment === 'alipay' }"
					@click="selectPayment('alipay')">
					<view class="method-icon">
						<uni-icons type="logo-alipay" size="24" color="#1677FF"></uni-icons>
					</view>
					<view class="method-name">支付宝</view>
					<view class="method-select" v-if="selectedPayment === 'alipay'">
						<uni-icons type="checkmark" size="20" color="#0000ff"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 优惠券选择 -->
		<view class="coupon-section">
			<view class="coupon-title">优惠券</view>
			<view class="coupon-selector" @click="goToCouponList">
				<text v-if="selectedVoucher">已选择: {{ selectedVoucher.amount.toFixed(2) }}元
					{{ selectedVoucher.title }}</text>
				<text v-else>未选择优惠券</text>
				<text class="arrow">→</text>
			</view>
		</view>

		<!-- 金额信息 -->
		<view class="amount-info">
			<view class="amount-item">
				<text class="amount-label">商品总价</text>
				<text class="amount-value">¥{{ totalPrice.toFixed(2) }}</text>
			</view>
			<view class="amount-item">
				<text class="amount-label">运费</text>
				<text class="amount-value">¥{{ shippingFee.toFixed(2) }}</text>
			</view>
			<view class="amount-item" v-if="selectedVoucher">
				<text class="amount-label">优惠</text>
				<text class="amount-value">-¥{{ selectedVoucher.amount.toFixed(2) }}</text>
			</view>
			<view class="amount-total">
				<text class="total-label">实付款</text>
				<text class="total-value">¥{{ actualPayment.toFixed(2) }}</text>
			</view>
		</view>

		<!-- 底部结算按钮 -->
		<view class="checkout-footer">
			<view class="total-amount">
				<text class="total-text">合计: </text>
				<text class="total-price">¥{{ actualPayment.toFixed(2) }}</text>
			</view>
			<view class="pay-btn" @click="submitOrder">
				提交订单
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cartList: [],
				selectedPayment: 'balance',
				shippingFee: 8.00,
				selectedVoucher: null,
			};
		},
		computed: {
			totalPrice() {
				return this.cartList.reduce((sum, item) => {
					// 确保价格和数量为有效数字
					const price = typeof item.price === 'number' ? item.price : 0;
					const quantity = typeof item.quantity === 'number' ? item.quantity : 0;
					return sum + (price * quantity);
				}, 0);
			},
			// 计算实付款
			actualPayment() {
				const voucherAmount = this.selectedVoucher ? Number(this.selectedVoucher.amount) || 0 : 0;
				// 实付款不小于0
				return Math.max(this.totalPrice + this.shippingFee - voucherAmount, 0);
			}
		},
		onLoad(options) {
			// 接收上一级（如商品详情页）传递的商品数据
			if (options.cartData) {
				try {
					const parsedData = JSON.parse(decodeURIComponent(options.cartData));
					this.cartList = Array.isArray(parsedData) ? parsedData : [];
				} catch (e) {
					console.error('解析商品数据失败：', e);
					uni.showToast({
						title: '商品数据错误',
						icon: 'none'
					});
					this.cartList = [];
				}
			}
		},
		onShow() {
			// 页面显示时读取选中的优惠券
			this.loadSelectedVoucher();
		},
		methods: {
			// 返回上一页
			navigateBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			// 选择支付方式
			selectPayment(method) {
				this.selectedPayment = method;
			},

			// 加载选中的优惠券
			loadSelectedVoucher() {
				const voucher = uni.getStorageSync('selectedVoucher');
				if (voucher && typeof voucher.amount === 'number') {
					this.selectedVoucher = voucher;
				} else {
					this.selectedVoucher = null;
				}
			},

			// 前往优惠券列表页
			goToCouponList() {
				uni.navigateTo({
					url: "/pages/discount/account" // 优惠券列表页路径
				});
			},

			// 提交订单时，验证支付方式并传递数据
			submitOrder() {
				if (!this.selectedPayment) {
					uni.showToast({
						title: '请选择支付方式',
						icon: 'none'
					});
					return;
				}

				if (this.actualPayment <= 0) {
					uni.showToast({
						title: '请检查订单信息',
						icon: 'none'
					});
					return;
				}

				uni.showLoading({
					title: '提交中...'
				});

				setTimeout(() => {
					uni.hideLoading();

					// 统一编码所有需要传递的参数
					const cartData = encodeURIComponent(JSON.stringify(this.cartList));
					const checkoutTotal = encodeURIComponent(this.actualPayment.toString());
					const paymentMethod = encodeURIComponent(this.selectedPayment);
					const shippingFee = encodeURIComponent(this.shippingFee.toString());
					const voucherAmount = this.selectedVoucher ? encodeURIComponent(this.selectedVoucher.amount
						.toString()) : '0';

					uni.navigateTo({
						url: `/pages/goodsDetail/payment?cartData=${cartData}&checkoutTotal=${checkoutTotal}&paymentMethod=${paymentMethod}&shippingFee=${shippingFee}&voucherAmount=${voucherAmount}`
					});

					// 清空选中的优惠券（可选）
					uni.removeStorageSync('selectedVoucher');
				}, 1500);
			},
		},
		watch: {
			// 监听购物车数据变化，自动重新计算
			cartList() {
				// 依赖计算属性自动更新
			},
			selectedVoucher() {
				// 优惠券变化时自动重新计算
			},
			shippingFee() {
				// 运费变化时自动重新计算
			}
		}
	};
</script>

<style scoped>
	.checkout-page {
		background-color: #f5f5f5;
		min-height: 120vh;
		font-size: 14px;
	}

	/* 商品列表样式 */
	.products-title {
		padding: 12px 16px;
		color: #999999;
		background-color: #f5f5f5;
	}

	.product-item {
		display: flex;
		padding: 16px;
		background-color: #ffffff;
		border-bottom: 1px solid #eeeeee;
	}

	.product-img {
		width: 80px;
		height: 80px;
		border-radius: 4px;
		margin-right: 12px;
	}

	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.product-name {
		color: #333333;
		margin-bottom: 4px;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		line-height: 1.4;
	}

	.product-spec {
		color: #999999;
		font-size: 12px;
		margin-bottom: 8px;
	}

	.product-price-count {
		display: flex;
		justify-content: space-between;
		margin-top: auto;
	}

	.product-price {
		color: #ff4d4f;
		font-weight: 500;
	}

	.product-count {
		color: #333333;
	}

	/* 支付方式样式 */
	.payment-method {
		background-color: #ffffff;
		margin-top: 10px;
		padding: 0 16px;
	}

	.method-title {
		padding: 16px 0;
		color: #333333;
		border-bottom: 1px solid #eeeeee;
	}

	.method-options {
		padding: 10px 0;
	}

	.method-option {
		display: flex;
		align-items: center;
		padding: 12px 0;
		border-bottom: 1px solid #eeeeee;
	}

	.method-option:last-child {
		border-bottom: none;
	}

	.method-icon {
		margin-right: 12px;
	}

	.method-name {
		flex: 1;
		color: #333333;
	}

	.method-select {
		color: #0000ff;
	}

	.method-option.selected {
		background-color: rgba(0, 122, 255, 0.15);
	}

	/* 优惠券样式 */
	.coupon-section {
		background-color: #ffffff;
		margin-top: 10px;
		padding: 0 16px;
	}

	.coupon-title {
		padding: 16px 0;
		color: #333333;
		border-bottom: 1px solid #eeeeee;
	}

	.coupon-selector {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16px 0;
		color: #666666;
	}

	.arrow {
		color: #ccc;
		font-size: 16px;
	}

	/* 金额信息样式 */
	.amount-info {
		background-color: #ffffff;
		margin-top: 10px;
		padding: 0 16px;
	}

	.amount-item {
		display: flex;
		justify-content: space-between;
		padding: 12px 0;
		border-bottom: 1px solid #eeeeee;
	}

	.amount-item:last-child {
		border-bottom: none;
	}

	.amount-label {
		color: #666666;
	}

	.amount-value {
		color: #333333;
	}

	.amount-value:nth-child(2) {
		color: #ff4d4f;
	}

	.amount-total {
		display: flex;
		justify-content: space-between;
		padding: 16px 0;
	}

	.total-label {
		color: #666666;
		font-weight: 500;
	}

	.total-value {
		color: #ff4d4f;
		font-size: 16px;
		font-weight: 600;
	}

	/* 底部结算样式 */
	.checkout-footer {
		display: flex;
		align-items: center;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50px;
		background-color: #ffffff;
		border-top: 1px solid #eeeeee;
		padding: 0 16px;
	}

	.total-amount {
		flex: 1;
	}

	.total-text {
		color: #666666;
	}

	.total-price {
		color: #ff4d4f;
		font-size: 16px;
		font-weight: 600;
	}

	.pay-btn {
		width: 120px;
		height: 40px;
		line-height: 40px;
		text-align: center;
		background-color: #ff4d4f;
		color: #ffffff;
		border-radius: 20px;
		font-weight: 500;
	}
</style>